let autocomplete; let address1Field; let address2Field; let postalField; let numberField; let districtField; let cityField; let stateField; let widgetId1; let event_info = new Object(); function initAutocomplete() { address1Field = document.querySelector("#ship-address"); address2Field = document.querySelector("#address2"); postalField = document.querySelector("#postcode"); numberField = document.querySelector("#number"); districtField = document.querySelector("#bairro"); cityField = document.querySelector("#locality"); stateField = document.querySelector("#state"); //# Check 3 characteres to enable autcomplete #// autocomplete = false; $("#ship-address").keyup(function (e) { if ($("#ship-address").val().length < 3 || $("#ship-address").val().length > 30) { e.stopImmediatePropagation(); } else if (autocomplete == false) { //Creating autcomplete object var point = new google.maps.LatLng(-22.176, -47.386); var circle = new google.maps.Circle({ center: point, radius: 350000, }); autocomplete = new google.maps.places.Autocomplete(address1Field, { componentRestrictions: { country: ["br"], }, location: point, fields: ["address_components", "geometry"], types: ["geocode"], }); autocomplete.setBounds(circle.getBounds()); autocomplete.setOptions({ strictBounds: true }); address1Field.focus(); google.maps.event.addListener( autocomplete, "place_changed", function () { const place = autocomplete.getPlace(); fillInAddress(place); } ); } }); } //Fill Address fields function fillInAddress(place) { let address1 = ""; let postcode = ""; let number = ""; let distric = ""; let city = ""; let state = ""; const params = new Proxy(new URLSearchParams(window.location.search), { get: (searchParams, prop) => searchParams.get(prop), }); event_info = { currentStep: 1, } bysideWebcare_event("PurchaseFunnelStep", event_info) //Iterando a resposta da API e preenchendo os campos for (const component of place.address_components) { const componentType = component.types[0]; switch (componentType) { //Rua case "route": { address1 = `${component.long_name}${address1}`; $("#ship-address").prop("disabled", false); break; } //Cidade case "administrative_area_level_2": { city = `${component.long_name}${city}`; $("#locality").prop("disabled", false); break; } //Estado case "administrative_area_level_1": { state = component.short_name; $("#state").prop("disabled", false); break; } //CEP case "postal_code": { postcode = `${component.long_name}${postcode}`; $("#postcode").prop("disabled", false); break; } case "postal_code_suffix": { postcode = `${postcode}-${component.long_name}`; $("#postcode").prop("disabled", false); break; } //Bairro case "sublocality_level_1": { distric = `${component.long_name}${distric}`; $("#bairro").prop("disabled", false); break; } //Número case "street_number": { number = `${number}${component.long_name}`; $("#number").prop("disabled", false); break; } } } address1Field.value = address1; cityField.value = city; stateField.value = state; postalField.value = postcode; districtField.value = distric; numberField.value = number; event_info = { step: 1, cep: postcode || address1 + ', ' + number, utm_medium: params.utm_medium, utm_source: params.utm_source, utm_campaign: params.utm_campaign, utm_content: params.utm_content, utm_term: params.utm_term, gclid: params.gclid } bysideWebcare_event('funil_recuperacao', event_info); displayFlex(); setInputFocus(); disableFields(); } function displayFlex() { $("body").addClass('form-started'); $(".locality").css("display", "flex"); $(".state").css("display", "flex"); $(".postcode").css("display", "flex"); $(".bairro").css("display", "flex"); $(".tipo-moradia").css("display", "flex"); $(".address2").css("display", "flex"); $(".number").css("display", "flex"); if ($("input#locality").val() == "") { var checkcep = $("input#ship-address").val(); if (addressNumber(checkcep)) { $("input#postcode").val(checkcep).trigger("input"); } $("input#ship-address").val(""); $("input#ship-address").attr( "placeholder", "(exemplo: Rua Emílio Leão Brambila 46, Sumaré)" ); $("label.shipping-adress span").text("Digite seu endereço*:"); Swal.fire({ icon: "info", title: "Ops...", text: "Endereço não encontrado, preencha novamente.", }); } } function setInputFocus() { $("form#address-form input").each(function () { if ($(this).val() == "") { $(this).trigger("focus"); return false; } }); } function disableFields() { $("#locality").prop("disabled", true); $("#state").prop("disabled", true); if ($("#locality").val() != "") { $("#locality").prop("disabled", true); } if ($("#state").val() != "") { $("#state").prop("disabled", true); } // if ($('#postcode').val() != '') { // $("#postcode").prop("disabled", true); // }; // if ($('#bairro').val() != '') { // $("#bairro").prop("disabled", true); // }; if ($("#number").val() != "") { $("#number").prop("disabled", true); } } function addressNumber(checkcep) { var re = /^\d+$/; return re.test(checkcep); } function emailValidate(mail) { var re = /^(([^<>()[\]\\.,;:\s@"\/'~:^=+\*\|\{\}%$#&!]+(\.[^<>()[\]\\.,;:\s@"\/'~:^=+\*\|\{\}%$#&!]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if(!re.test(mail)) return false; var emailBlackList = ['naotem', 'nao.tem', 'nao_tem', 'naoinformado', 'naopossui', 'naopossuo', 'sememail', 'naotem', 'nao.tem', 'nao_tem']; var emailSuffix = mail.split('@')[0]; var emailDomain = (mail.split('@')[1]).split('.')[0]; if(emailBlackList.includes(emailDomain) || emailSuffix.length < 2 || emailDomain.length < 2) return false; return true; } function phoneValidate(telephone) { var re = /^(?:(?:\+|00)?(55)\s?)?(?:\(?([1-9][1-9])\)?\s?)?(?:((?:9\d|[2-9])\d{3})\-?(\d{4}))$/; if(!re.test(telephone)) return false; var regExpCel = /(\d)\1{7}/; if(regExpCel.test((re.exec(telephone)[3].concat(re.exec(telephone)[4])).slice(1))) return false; return true; } function nameValidate(name) { var re = /\s/g; return re.test(name); } function complementValidate(complementToValidate) { var re = /\w{3}/; return re.test(complementToValidate); } function tipoResidencia() { if ( $("#tipo-moradia").val() == "Condomínio de Casas" || $("#tipo-moradia").val() == "Condomínio de Prédios" || $("#tipo-moradia").val() == "Prédio" ) { return true; } else { return false; } } function isValidFormStep1() { var address = document.getElementById("ship-address").value; var distric = document.getElementById("bairro").value; var home = document.getElementById("tipo-moradia").value; var complement = document.getElementById("address2").value; var number = document.getElementById("number").value; var postcode = document.getElementById("postcode").value; if (!address) { Swal.fire({ icon: "info", title: "Ops... Faltou o endereço", text: "Para continuar, é preciso preencher um endereço válido.", }); return false; } //Checando se o CEP está preechido if (!postcode) { Swal.fire({ icon: "info", title: "Ops... Faltou o CEP", text: "Para continuar, é preciso preencher o CEP da residência.", }); return false; } //Checando se o bairro está preechido if (!distric) { Swal.fire({ icon: "info", title: "Ops... Faltou o bairro", text: "Para continuar, é preciso preencher o bairro da residência.", }); return false; } //Checando se o número está preechido if (!number) { Swal.fire({ icon: "info", title: "Ops... Faltou o número", text: "Para continuar, é preciso preencher o número da residência.", }); return false; } // Checando se o tipo de residência está preenchido if (home == "null") { Swal.fire({ icon: "info", title: "Ops... Faltou informar o tipo de residência", text: "Para continuar, é preciso preencher o tipo de residência.", }); return false; } // Checando se o tipo de residência está preenchido if (!complement && tipoResidencia()) { Swal.fire({ icon: "info", title: "Ops... Faltou complementar o endereço", text: "Para continuar, é preciso preencher o complemento do endereço (apto, bloco, casa).", }); return false; } if (complementValidate(complement) == false && tipoResidencia()) { Swal.fire({ icon: "info", title: "Ops... Complemento inválido", text: "Para continuar, é preciso preencher o complemento corretamente.", }); return false; } return true; } function isValidFormStep2() { var name = document.getElementById("name").value; var telephone = document.getElementById("telephone").value; var mail = document.getElementById("mail").value; var terms = jQuery("input#terms:checked").length; //Checando se o nome está preechido if (!name) { Swal.fire({ icon: "info", title: "Ops... Faltou o nome", text: "Para continuar, é preciso preencher o nome completo.", }); return false; } //Checando se o nome é Válido if (nameValidate(name) == false) { Swal.fire({ icon: "info", title: "Ops... Nome inválido", text: "Para continuar, é preciso preencher um nome completo válido.", }); return false; } //Checando se o telefone está preechido if (!telephone) { Swal.fire({ icon: "info", title: "Ops... Faltou o celular", text: "Para continuar, é preciso preencher um número de celular válido (Whatsapp).", }); return false; } // //Checando se o telefone é valido if (phoneValidate(telephone) == false) { Swal.fire({ icon: "info", title: "Ops... Telefone inválido", text: "Para continuar, é preciso preencher um número de telefone válido.", }); return false; } // //Checando se o email está preechido if (!mail) { Swal.fire({ icon: "info", title: "Ops... Faltou o e-mail", text: "Para continuar, é preciso preencher um e-mail válido.", }); return false; } // //Checando se o email é valido if (emailValidate(mail) == false) { Swal.fire({ icon: "info", title: "Ops... E-mail inválido", text: "Para continuar, é preciso preencher um e-mail válido.", }); return false; } //Checando se os termos de uso foram aceitos if (terms < 1) { Swal.fire({ icon: "info", title: "Ops... Faltou aceitar os termos", text: "Para continuar, é preciso aceitar os Termos de uso e Políticas de privacidade.", }); return false; } return true; } function enablePersonalDataFields() { $(".name").css("display", "flex"); $(".telephone").css("display", "flex"); $(".mail").css("display", "flex"); $(".terms").css("display", "flex"); $("#ship-address").prop("disabled", true); $("#postcode").prop("disabled", true); $("#bairro").prop("disabled", true); $("#number").prop("disabled", true); $("#address2").prop("disabled", true); $("#tipo-moradia").prop("disabled", true); $("#ship-address").prop("disabled", true); $("button#callGeocode").text("Consultar disponibilidade"); var url = location.href; location.href = "#name"; history.replaceState(null, null, url); } //Interação com o Geocode function geocodeAPICall() { const params = new Proxy(new URLSearchParams(window.location.search), { get: (searchParams, prop) => searchParams.get(prop), }); var address = document.getElementById("ship-address").value; var number = document.getElementById("number").value; var city = document.querySelector("#locality").value; var postalCode = document.getElementById("postcode").value; var district = document.getElementById("bairro").value; var addressType = document.getElementById("tipo-moradia").value; var complement = document.getElementById("address2").value; var state = "SP"; var country = "Brasil"; if ( $("#postcode:visible").length < 1 && document.getElementById("ship-address").value != "" ) { displayFlex(); return false; } if (!isValidFormStep1()) { return false; } if ($("#name:visible").length < 1) { event_info = { currentStep: 2 }; bysideWebcare_event("PurchaseFunnelStep", event_info); event_info = { step: 2, cep: postalCode, endereco: address, cidade: city, bairro: district, numero: number, tipo_residencia: addressType, complemento: complement, utm_medium: params.utm_medium, utm_source: params.utm_source, utm_campaign: params.utm_campaign, utm_content: params.utm_content, utm_term: params.utm_term, gclid: params.gclid }; bysideWebcare_event("funil_recuperacao", event_info); enablePersonalDataFields(); return false; } if (!isValidFormStep2()) { return false; } //Montando a string de chamada var queryString = `${address},${number},${city},${state},${country}`; //Realizando o request para o GEOCODE var Geocoder = new google.maps.Geocoder(); Geocoder.geocode({ address: queryString }, function (results, status) { for (let i = 0; i < results.length; i++) { var lat = JSON.parse( JSON.stringify(results[i]["geometry"]["location"]) ).lat; var lng = JSON.parse( JSON.stringify(results[i]["geometry"]["location"]) ).lng; var clientData = { street: document.querySelector("#ship-address").value, city: document.querySelector("#locality").value, state: document.querySelector("#state").value, postalCode: document.querySelector("#postcode").value, distric: document.querySelector("#bairro").value, number: document.querySelector("#number").value, type: document.querySelector("#tipo-moradia").value, street2: document.querySelector("#address2").value, fullName: document.querySelector("#name").value, phone: document.querySelector("#telephone").value, email: document.querySelector("#mail").value, lat: lat.toString(), lng: lng.toString(), // RD Station Fields eventType: "CONVERSION", eventFamily: "CDP", conversionIdentifier: "E-COMMERCE", country: "BRASIL", trafficSource: params.utm_source, trafficMedium: params.utm_medium, trafficCampaign: params.utm_campaign, trafficValue: params.utm_term, status: "", optionalMessage: "", initialConversion: "", leadsForaDiscador: "Sim" }; $("body").spinner().start(); $("body").addClass("modal-open"); $.ajax({ url: $("#address-form").data("url"), type: "POST", dataType: "json", data: clientData, success: function (data, textStatus, jQxhr) { if (data.unavailableReason !== "TIMEOUT") { event_info = { currentStep: 3, }; bysideWebcare_event('PurchaseFunnelStep', event_info); event_info = { step: 3, cep: document.getElementById("postcode").value, endereco: document.getElementById("ship-address").value, cidade: document.getElementById("locality").value, bairro: document.getElementById("bairro").value, numero: document.getElementById("number").value, tipo_residencia: document.getElementById("tipo-moradia").value, complemento: document.getElementById("address2").value, nome: document.getElementById("name").value, telefone: '55' + document.getElementById("telephone").value.replace(/\D/g, ''), email: document.getElementById("mail").value, termos_condicoes: jQuery("input#terms:checked").length ? "1" : "0", utm_medium: params.utm_medium, utm_source: params.utm_source, utm_campaign: params.utm_campaign, utm_content: params.utm_content, utm_term: params.utm_term, gclid: params.gclid }; bysideWebcare_event("funil_recuperacao", event_info); // Salvar no localStorage var event_info_str = JSON.stringify(event_info); localStorage.setItem('event_info', event_info_str); setTimeout(() => { window.location = data.redirectTo; }, 500); $.spinner().stop(); $("body").removeClass("modal-open"); } else { $("p#timeout-message").show(); $.ajax({ url: $("#address-form").data("url"), type: "POST", dataType: "json", data: clientData, success: function (data, textStatus, jQxhr) { event_info = { currentStep: 3, }; bysideWebcare_event('PurchaseFunnelStep', event_info); event_info = { step: 3, cep: document.getElementById("postcode").value, endereco: document.getElementById("ship-address").value, cidade: document.getElementById("locality").value, bairro: document.getElementById("bairro").value, numero: document.getElementById("number").value, tipo_residencia: document.getElementById("tipo-moradia").value, complemento: document.getElementById("address2").value, nome: document.getElementById("name").value, telefone: '55' + document.getElementById("telephone").value.replace(/\D/g, ''), email: document.getElementById("mail").value, termos_condicoes: jQuery("input#terms:checked").length ? "1" : "0", utm_medium: params.utm_medium, utm_source: params.utm_source, utm_campaign: params.utm_campaign, utm_content: params.utm_content, utm_term: params.utm_term, gclid: params.gclid }; bysideWebcare_event("funil_recuperacao", event_info); // Salvar no localStorage var event_info_str = JSON.stringify(event_info); localStorage.setItem('event_info', event_info_str); setTimeout(() => { window.location = data.redirectTo; }, 500); $.spinner().stop(); $("body").removeClass("modal-open"); }, error: function (jqXhr, textStatus, errorThrown) { Swal.fire({ icon: "error", title: "Erro", text: "Tente novamente", }); $.spinner().stop(); $("body").removeClass("modal-open"); }, }); } }, error: function (jqXhr, textStatus, errorThrown) { Swal.fire({ icon: "error", title: "Erro", text: "Tente novamente", }); $.spinner().stop(); $("body").removeClass("modal-open"); }, }); } }); } function getAddress(token) { $.ajax({ url: $("#address-form").data("googleurl"), type: "POST", dataType: "json", data: { token: token, }, success: function (data, textStatus, jQxhr) { if ( data.data.score > $("#divHead").data("google-recaptcha-score") || document.getElementById("name").value === "" ) { geocodeAPICall(); } else { if (isValidFormStep2()) { $("#recaptchaV2").css("display", "block"); widgetId1 = grecaptcha.ready(function () { grecaptcha.render("recaptchaV2", { sitekey: $("#divHead").data( "google-recaptcha-v2-key" ), }); }); } } }, error: function (jqXhr, textStatus, errorThrown) { Swal.fire({ icon: "error", title: "Erro", text: "Tente novamente", }); }, }); } function bindProceed() { $("#callGeocode").click(function () { if ($("#name:visible").length < 1) { geocodeAPICall(); } else if ($("#recaptchaV2:visible").length < 1) { grecaptcha.ready(function () { grecaptcha .execute($("#divHead").data("google-recaptcha-key"), { action: "submit", }) .then(function (token) { getAddress(token); }); }); } else { $.ajax({ url: $("#address-form").data("googlev2url"), type: "POST", dataType: "json", data: { token: grecaptcha.getResponse(widgetId1), }, success: function (data, textStatus, jQxhr) { if (data.data.success) { if (isValidFormStep2()) { geocodeAPICall(); } else { grecaptcha.reset(widgetId1); } } }, error: function (jqXhr, textStatus, errorThrown) { Swal.fire({ icon: "error", title: "Erro", text: "Tente novamente", }); }, }); } }); } function bindHouseType() { $("#tipo-moradia").on("change", function () { if ( $("#tipo-moradia").val() == "Condomínio de Casas" || $("#tipo-moradia").val() == "Condomínio de Prédios" || $("#tipo-moradia").val() == "Prédio" ) { $("input#address2").parent().addClass("required"); $("input#address2").addClass("required"); } else { $("input#address2").parent().removeClass("required"); $("input#address2").removeClass("required"); } }); } $("#tipo-moradia").on("change", function () { var tipoMoradia = $("#tipo-moradia").val(); if (tipoMoradia === "null") { $("#tipo-moradia").val(""); $("#tipo-moradia") .siblings(".invalid-feedback") .text("Selecione o tipo de residência"); $("#tipo-moradia").siblings(".invalid-feedback").show(); $("#tipo-moradia").css({ borderColor: "#F00", }); } else { $("#tipo-moradia").siblings(".invalid-feedback").text(""); $("#tipo-moradia").siblings(".invalid-feedback").hide(); $("#tipo-moradia").css({ borderColor: " #090", }); } }); $("#address2").on("change", function () { var complement = $("#address2").val(); if (!complement && tipoResidencia() === false) { $("#address2").val(""); $("#address2") .siblings(".invalid-feedback") .text( "Para continuar, é preciso preencher o complemento do endereço (apto, bloco, casa)." ); $("#address2").siblings(".invalid-feedback").show(); $("#address2").css({ borderColor: "#F00", }); } else if (complementValidate(complement) == false && tipoResidencia()) { $("#address2").val(""); $("#address2") .siblings(".invalid-feedback") .text( "Para continuar, é preciso preencher o complemento corretamente(apto, bloco, casa)." ); $("#address2").siblings(".invalid-feedback").show(); $("#address2").css({ borderColor: "#F00", }); } else { $("#address2").siblings(".invalid-feedback").text(""); $("#address2").siblings(".invalid-feedback").hide(); $("#address2").css({ borderColor: " #090", }); } }); $("#number").on("change", function () { if (number.value === "") { $("#number").val(""); $("#number") .siblings(".invalid-feedback") .text( "Campo número vazio, por gentileza digite o número da residência" ); $("#number").siblings(".invalid-feedback").show(); $("#number").css({ borderColor: "#F00", }); } else { $("#number").siblings(".invalid-feedback").text(""); $("#number").siblings(".invalid-feedback").hide(); $("#number").css({ borderColor: " #090", }); } }); $("#name").on("change", function () { var name = document.getElementById("name").value; if (nameValidate(name) == false) { $("#name").val(""); $("#name") .siblings(".invalid-feedback") .text("Nome inválido, por gentileza digite um nome válido"); $("#name").siblings(".invalid-feedback").show(); $("#name").css({ borderColor: "#F00", }); } else { $("#name").siblings(".invalid-feedback").text(""); $("#name").siblings(".invalid-feedback").hide(); $("#name").css({ borderColor: " #090", }); } }); $("#telephone").on("change", function () { if (phoneValidate(telephone.value) == false) { $("#telephone").val(""); $("#telephone ") .siblings(".invalid-feedback") .text( "Número de telefone inválido, por gentileza digite um número de telefone válido" ); $("#telephone ").siblings(".invalid-feedback").show(); $("#telephone ").css({ borderColor: "#F00", }); } else { $("#telephone").siblings(".invalid-feedback").text(""); $("#telephone ").siblings(".invalid-feedback").hide(); $("#telephone ").css({ borderColor: " #090", }); } }); $("#mail").on("change", function () { if (emailValidate(mail.value) == false) { $("#mail").val(""); $("#mail") .siblings(".invalid-feedback") .text("Email inválido, por gentileza digite um email válido"); $("#mail").siblings(".invalid-feedback").show(); $("#mail").css({ borderColor: "#F00", }); } else { $("#mail").siblings(".invalid-feedback").text(""); $("#mail").siblings(".invalid-feedback").hide(); $("#mail").css({ borderColor: " #090", }); } }); //binds $(function () { bindProceed(); bindHouseType(); });